import { Response } from 'express'
import { ApiError } from '../types/api'

// 错误代码枚举
export enum ErrorCode {
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  PLAYER_NOT_FOUND = 'PLAYER_NOT_FOUND',
  PLAYER_ID_EXISTS = 'PLAYER_ID_EXISTS',
  DATABASE_ERROR = 'DATABASE_ERROR',
  INTERNAL_ERROR = 'INTERNAL_ERROR'
}

// 自定义错误类
export class AppError extends Error {
  public readonly code: ErrorCode
  public readonly statusCode: number
  public readonly details?: any

  constructor(code: ErrorCode, message: string, statusCode: number = 500, details?: any) {
    super(message)
    this.code = code
    this.statusCode = statusCode
    this.details = details
    this.name = 'AppError'
  }
}

// 错误响应辅助函数
export const sendError = (res: Response, error: AppError): void => {
  const errorResponse: ApiError = {
    success: false,
    error: {
      code: error.code,
      message: error.message,
      details: error.details
    }
  }

  res.status(error.statusCode).json(errorResponse)
}

// 常用错误创建函数
export const createValidationError = (message: string, details?: any): AppError => {
  return new AppError(ErrorCode.VALIDATION_ERROR, message, 400, details)
}

export const createNotFoundError = (resource: string = '资源'): AppError => {
  return new AppError(ErrorCode.PLAYER_NOT_FOUND, `${resource}不存在`, 404)
}

export const createConflictError = (message: string): AppError => {
  return new AppError(ErrorCode.PLAYER_ID_EXISTS, message, 409)
}

export const createDatabaseError = (message: string = '数据库操作失败'): AppError => {
  return new AppError(ErrorCode.DATABASE_ERROR, message, 500)
}

export const createInternalError = (message: string = '服务器内部错误'): AppError => {
  return new AppError(ErrorCode.INTERNAL_ERROR, message, 500)
}
